package com.budwk.app.sqfwV2.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.budwk.app.oss.services.SysOssService;
import com.budwk.app.sqfw.constants.SqfwFormSummaryConstants;
import com.budwk.app.sqfw.models.Sqfw_completeflow;
import com.budwk.app.sqfw.models.Sqfw_formSummary_new;
import com.budwk.app.sqfw.services.SqfwCompleteflowService;
import com.budwk.app.sqfw.services.SqfwFormsummaryNewService;
import com.budwk.app.sqfw.vo.GenerateExcelUrlVO;
import com.budwk.app.sqfwDoc.bo.ExcelCreateConfig;
import com.budwk.app.sqfwDoc.codeGeneratorV2.fileParam.CompleteFlowExcelParamForController;
import com.budwk.app.sqfwDoc.codeGeneratorV2.fileParam.CompleteFlowPdfParamForController;
import com.budwk.app.sqfwDoc.codeGeneratorV2.generate.ResultOfExcelGenerator;
import com.budwk.app.sqfwV2.dto.LandscapePatrolDTO;
import com.budwk.app.sqfwV2.enums.LandscapePatrolEnum;
import com.budwk.app.sqfwV2.service.landscapePatrol.LandscapePatrolExcelService;
import com.budwk.app.sqfwV2.service.landscapePatrol.LandscapePatrolPdfService;

import com.budwk.app.sys.models.Sys_user;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.app.util.poiUtils.CommonFormOfficeUtils;
import com.budwk.starter.common.openapi.annotation.ApiDefinition;
import com.budwk.starter.common.openapi.annotation.ApiOperation;
import com.budwk.starter.common.result.Result;
import com.budwk.starter.security.utils.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.nutz.aop.interceptor.ioc.TransAop;
import org.nutz.dao.Cnd;
import org.nutz.ioc.aop.Aop;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.util.NutMap;
import org.nutz.mvc.annotation.*;


import javax.swing.*;
import java.util.*;
import java.util.stream.Collectors;

@IocBean
@At("/platform/sqfwV2/LandscapePatrol")
@ApiDefinition(tag = "会议/活动/巡逻走访")
@Slf4j
public class LandscapePatrolController {
    @Inject
    private LandscapePatrolPdfService landscapePatrolPdfService;
    @Inject
    private LandscapePatrolExcelService landscapePatrolExcelService;
    @Inject
    private SqfwFormsummaryNewService sqfwFormsummaryNewService;

    @Inject
    private SqfwCompleteflowService sqfwCompleteflowService;

    @Inject
    private SysOssService sysOssService;
    @Inject
    private SysUserService sysUserService;

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "提交数据/生成PDF")
    @SaCheckLogin
    @Aop(TransAop.READ_COMMITTED)
    public Result<?> addLandscapePatrol(@Param("..") CompleteFlowPdfParamForController paramForController) {
        landscapePatrolPdfService.createPdfAndMsg(paramForController);
        return Result.success();
    }

    @At
    @Ok("json")
    @GET
    @ApiOperation(name = "提交数据/生成PDF")
    @SaCheckLogin
    public Result<?> getAddressList(@Param("address")String address) {
        Sys_user sysUser=sysUserService.getUserById(SecurityUtil.getUserId());
        List<Sqfw_formSummary_new>  formSummaryNewList =  sqfwFormsummaryNewService.query(Cnd.where(Sqfw_formSummary_new::getType,"=", SqfwFormSummaryConstants.forest_and_river_flood_disaster)
                .and(Sqfw_formSummary_new::getProvince,"=",sysUser.getProvince())
                .and(Sqfw_formSummary_new::getCity,"=",sysUser.getCity())
                .and(Sqfw_formSummary_new::getDistrict,"=",sysUser.getDistrict())
                .and(Sqfw_formSummary_new::getCounty,"=",sysUser.getCounty())
                .and(Sqfw_formSummary_new::getCommunity,"=",sysUser.getCommunity())
                .and("param_data->>'address'","like","%" + address + "%"));

        List<NutMap> nutMaps=new ArrayList<>();
        Map<String,List<Sqfw_formSummary_new>> mapList=formSummaryNewList.stream().collect(Collectors.groupingBy(s->JSONUtil.toBean(s.getParamData(),LandscapePatrolDTO.class).getAddress()));
        for (String a : mapList.keySet()) {
            List<Sqfw_formSummary_new> list=mapList.get(a);
            List<Sqfw_formSummary_new> listOrder =  list.stream().sorted(Comparator.comparing(Sqfw_formSummary_new::getCreateDate).reversed())
                    .collect(Collectors.toList());
            LandscapePatrolDTO landscapePatrolDTO=JSONUtil.toBean(listOrder.get(0).getParamData(),LandscapePatrolDTO.class);
            nutMaps.add(NutMap.NEW().addv("id",listOrder.get(0).getId())
                    .addv("placeName",landscapePatrolDTO.getAddress())
                    .addv("createDate",listOrder.get(0).getCreateDate()));
        }

        return Result.data(nutMaps);
    }

    @At
    @Ok("json")
    @GET
    @ApiOperation(name = "提交数据/生成PDF")
    @SaCheckLogin
    public Result<?> getLandscapePatrol(@Param("id") String id) {
        return Result.data(sqfwFormsummaryNewService.fetch(id));
    }
    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "提交数据/生成PDF")
    @SaCheckLogin
    public Result<?> dataLabel(@Param("sqfwId") String sqfwId) {
        Set<String> label=new HashSet<>();
        int a = sqfwFormsummaryNewService.count(Cnd.where(Sqfw_formSummary_new::getSqfwId,"=",sqfwId)
                .and("param_data->>'patrolType'","=", LandscapePatrolEnum.A.getName()));
        if(a>0){
            label.add("1");
            label.add("4");
        }
        int b = sqfwFormsummaryNewService.count(Cnd.where(Sqfw_formSummary_new::getSqfwId,"=",sqfwId)
                .and("param_data->>'patrolType'","=",LandscapePatrolEnum.B.getName()));
        if(b>0){
            label.add("2");
            label.add("5");
        }
        int c = sqfwFormsummaryNewService.count(Cnd.where(Sqfw_formSummary_new::getSqfwId,"=",sqfwId)
                .and("param_data->>'patrolType'","=",LandscapePatrolEnum.C.getName()));
        if(c>0){
            label.add("3");
            label.add("6");
        }
        return Result.data(label);
    }

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "提交数据/生成PDF")
    @SaCheckLogin
    public Result<?> downPdfLedger(@Param("sqfwId")String sqfwId,@Param("code")Integer code,@Param("isDownTemplate")boolean isDownTemplate) {
        List<GenerateExcelUrlVO> generateExcelUrlVOS = new ArrayList<>();
        GenerateExcelUrlVO generateExcelUrlVO = new GenerateExcelUrlVO();
        generateExcelUrlVOS.add(generateExcelUrlVO);
        if (isDownTemplate) {
            String filePath = LandscapePatrolEnum.getBlankTemplate(code);
            String fileName =filePath.substring(filePath.lastIndexOf("/")+1);
            generateExcelUrlVO.setExcelUrl( sysOssService.upload( CommonFormOfficeUtils.getTempPdfFile(filePath),fileName).getUrl());
        } else {
            List<Sqfw_formSummary_new>  formSummaryList = sqfwFormsummaryNewService.query(Cnd.where(Sqfw_formSummary_new::getSqfwId,"=",sqfwId)
                    .and("param_data->>'patrolType'","=",LandscapePatrolEnum.getName(code)));

            if (CollectionUtil.isNotEmpty(formSummaryList)) {
                List<String> summaryIdS = formSummaryList.stream().map(Sqfw_formSummary_new::getSqfwFlowId).collect(Collectors.toList());
                List<Sqfw_completeflow>  completeflow= sqfwCompleteflowService.query(Cnd.where(Sqfw_completeflow::getId, "in", summaryIdS)
                        .and(Sqfw_completeflow::getResourcePath, "!=", "creating")
                        .and(Sqfw_completeflow::getResourcePath, "!=", "error"));
                if (CollectionUtil.isNotEmpty(completeflow)) {

                    List<String> pdfPathList = completeflow.stream().map(Sqfw_completeflow::getResourcePath).collect(Collectors.toList());
                    String url = CommonFormOfficeUtils.createConvergePdfAndUpload(pdfPathList, LandscapePatrolEnum.getFileName(code));
                    generateExcelUrlVO.setExcelUrl(url);
                }
            }
        }
        return Result.data( generateExcelUrlVOS);
    }

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "提交数据/生成PDF")
    @SaCheckLogin
    public Result<?> downExcelLedger(@Param("sqfwId")String sqfwId,@Param("code")Integer code,@Param("isDownTemplate")boolean isDownTemplate) {
        List<GenerateExcelUrlVO> generateExcelUrlVOS = new ArrayList<>();
        GenerateExcelUrlVO generateExcelUrlVO = new GenerateExcelUrlVO();
        generateExcelUrlVOS.add(generateExcelUrlVO);
        if (isDownTemplate) {
            String filePath = LandscapePatrolEnum.getBlankTemplate(code);
            String fileName =filePath.substring(filePath.lastIndexOf("/")+1);
            generateExcelUrlVO.setExcelUrl( sysOssService.upload( CommonFormOfficeUtils.getTempPdfFile(filePath),fileName).getUrl());
        } else {
            CompleteFlowExcelParamForController paramForController=new CompleteFlowExcelParamForController();
            paramForController.setSqfwId(sqfwId);
            List<ExcelCreateConfig> excelCreateConfigList=new ArrayList<>();
            ExcelCreateConfig excelCreateConfig =  new ExcelCreateConfig();
            excelCreateConfig.setFileIdentity(String.valueOf(code));
            excelCreateConfigList.add(excelCreateConfig);
            paramForController.setExcelCreateConfigList(excelCreateConfigList);
            paramForController.setUserId(SecurityUtil.getUserId());
            List<ResultOfExcelGenerator> excel =  landscapePatrolExcelService.createExcel(paramForController);

            if (CollectionUtil.isNotEmpty(excel)) {
                generateExcelUrlVO.setExcelUrl(excel.get(0).getExcelUrl());
            }
        }
        return Result.data( generateExcelUrlVOS);
    }
}
